package com.itheima.tlias08_14.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias08_14.dto.LoginDTO;
import com.itheima.tlias08_14.entity.Emp;
import com.itheima.tlias08_14.mapper.EmpMapper;
import com.itheima.tlias08_14.paramobject.LoginPO;
import com.itheima.tlias08_14.service.LoginService;
import com.itheima.tlias08_14.utils.JwtUtil;
import com.itheima.tlias08_14.utils.ResultUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImp implements LoginService {
    @Resource
    EmpMapper mapper;
    @Override
    public ResultUtil selectByUsername(LoginPO lpo) {
        LoginDTO emp = mapper.selectByUsername(lpo.getUsername());
        if (emp!= null && emp.getPassword().equals(lpo.getPassword())){

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username", emp.getUserName());
            jsonObject.put("password", emp.getPassword());
            String temporaryToken = JwtUtil.createTemporaryToken(emp.getUserName(), emp.getPassword(), 1000000);
            jsonObject.put("token", temporaryToken);
            System.out.println("解码："+JwtUtil.decode(temporaryToken));
            return ResultUtil.success(jsonObject);
        }
        if(emp == null){
            return ResultUtil.failure("用户不存在");
        }
        if(!Objects.equals(emp.getPassword(), lpo.getPassword())){
            return ResultUtil.failure("用户密码不正确");
        }
        return ResultUtil.failure();
    }
}
